package com.cjlgb.design.oauth.receiver;

import com.cjlgb.design.oauth.channel.AccountInputChannel;
import com.cjlgb.design.oauth.entity.Oauth2AccountDetails;
import com.cjlgb.design.oauth.service.OauthAccountService;
import com.cjlgb.design.upms.api.entity.Oauth2Account;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author WFT
 * @date 2019/8/29
 * description: oauth2 账户,异步接口消费逻辑
 */
@Slf4j
@Component
@RequiredArgsConstructor
@EnableBinding(value = AccountInputChannel.class)
public class OauthAccountReceiver {

    private final OauthAccountService accountService;
    private final PasswordEncoder passwordEncoder;

    /**
     * 监听删除用户缓存
     * @param names 用户名列表
     */
    @StreamListener(value = AccountInputChannel.INPUT, condition = "headers['method']=='deleteCache'")
    public void listenerDeleteCache(Collection<String> names){
        names.forEach(this.accountService::deleteCacheByUsername);
    }

    /**
     * 监听用户添加
     * @param account 用户信息
     */
    @StreamListener(value = AccountInputChannel.INPUT, condition = "headers['method']=='add'")
    public void listenerAddAdminUser(Oauth2Account account){
        Oauth2AccountDetails details = new Oauth2AccountDetails();
        details.setId(account.getId());
        details.setUsername(account.getUsername());
        details.setPassword(this.passwordEncoder.encode(account.getPassword()));
        details.setLockFlag(account.getLockFlag());
        details.setUserFlag(account.getUserFlag());
        this.accountService.save(details);
    }

    /**
     * 监听用户的锁定状态发生改变
     * @param account 用户信息
     */
    @StreamListener(value = AccountInputChannel.INPUT, condition = "headers['method']=='isEnable'")
    public void listenerIsEnable(Oauth2Account account) {
        this.accountService.editLockFlag(account.getUsername(),account.getLockFlag());
    }

    /**
     * 监听用户被删除
     * @param accountIds 账号Id列表
     */
    @StreamListener(value = AccountInputChannel.INPUT, condition = "headers['method']=='delete'")
    public void listenerDelete(Collection<Long> accountIds){
        //  获取账号的用户名
        Collection<String> names = this.accountService.listByIds(accountIds)
                .stream().map(Oauth2AccountDetails::getUsername).collect(Collectors.toList());
        //  删除账号
        this.accountService.removeByIds(accountIds);
        //  删除缓存
        this.listenerDeleteCache(names);
    }
}
